package com.jspxcms.core.web.fore;

import com.jspxcms.common.web.Servlets;
import com.jspxcms.core.domain.GlobalRegister;
import com.jspxcms.core.domain.Site;
import com.jspxcms.core.domain.User;
import com.jspxcms.core.domain.UserDetail;
import com.jspxcms.core.security.CmsAuthenticationFilter;
import com.jspxcms.core.service.OrgService;
import com.jspxcms.core.service.ScoreService;
import com.jspxcms.core.service.UserDetailService;
import com.jspxcms.core.service.UserService;
import com.jspxcms.core.support.Context;
import com.jspxcms.core.support.ForeContext;
import com.qq.connect.QQConnectException;
import com.qq.connect.api.OpenID;
import com.qq.connect.api.qzone.UserInfo;
import com.qq.connect.javabeans.AccessToken;
import com.qq.connect.oauth.Oauth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import weibo4j.Account;
import weibo4j.Users;
import weibo4j.model.WeiboException;
import weibo4j.org.json.JSONException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

import static com.jspxcms.core.security.CmsAuthenticationFilter.FALLBACK_URL_PARAM;


@Controller
public class OAuthController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserDetailService userDetailService;
    @Autowired
    private ScoreService scoreService;
    @Autowired
    CmsAuthenticationFilter authenticationFilter;
    private String OauthCheck_TEMPLATE = "oauth_check.html";

    @RequestMapping("/oauth/check.jspx")
    public String check(String uid, String from, HttpServletRequest request, HttpServletResponse response, org.springframework.ui.Model modelMap) {
        User user = null;
        String qquid = null;
        String sinauid = null;
        String nickName = null;
        Site site = Context.getCurrentSite(request);

        /*******qq授权验证*************/
        try {
            AccessToken accessTokenObj = (new Oauth()).getAccessTokenByRequest(request);

            String accessToken, openID;

            if (accessTokenObj.getAccessToken().equals("")) {
                System.out.print("没有获取到响应参数");
            } else {
                accessToken = accessTokenObj.getAccessToken();
                // 利用获取到的accessToken 去获取当前用的openid -------- start
                OpenID openIDObj = new OpenID(accessToken);
                openID = openIDObj.getUserOpenID();
                from = "qq";
                uid = openID;
                qquid = uid;
                UserInfo qzoneUserInfo = new UserInfo(accessToken, openID);
                nickName = qzoneUserInfo.getUserInfo().getNickname();
            }
        } catch (QQConnectException e) {
            e.printStackTrace();
        }
        /********微博授权登录****************/
        try {
            String code = request.getParameter("code");
            if (code != null && code.length() > 0) {
                weibo4j.http.AccessToken accessTokenByCode = new weibo4j.Oauth().getAccessTokenByCode(code);
                Users um = new Users(accessTokenByCode.getAccessToken());
                Account am = new Account(accessTokenByCode.getAccessToken());
                from = "sina";
                uid = am.getUid().getString("uid");
                sinauid = uid;
            }
        } catch (WeiboException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        /***********************/
        if (uid != null && uid.length() > 0) {
            if ("sina".equalsIgnoreCase(from)) {
                user = userService.findByOauthSinaUid(uid);
                sinauid = uid;
            }
            if ("qq".equalsIgnoreCase(from)) {
                user = userService.findByOauthQqUid(uid);
                qquid = uid;
            }
        }
        if (uid != null && uid.length() > 0 && user == null) {
            String ip = Servlets.getRemoteAddr(request);
            GlobalRegister reg = site.getGlobal().getRegister();

            int groupId = reg.getGroupId();
            int orgId = reg.getOrgId();
            user = userService.register(ip, groupId, orgId, User.NORMAL, from + uid,
                    "123456", "", "F", new Date(), "", "", "", "",
                    "", nickName == null ? from + uid : nickName, "", "", "", sinauid, qquid, "sms");
            UserDetail score_reg = scoreService.updateScore(user.getDetail(), "score_reg");
            userDetailService.update(score_reg);
        }
        Map<String, Object> data = modelMap.asMap();
        ForeContext.setData(data, request);
        data.put("user", user);
        data.put("from", from);
        data.put("uid", uid);
        return site.getTemplate(OauthCheck_TEMPLATE);
    }

    @RequestMapping("/oauth/checkqq.jspx")
    public void checkqq(String uid, String from, HttpServletRequest request, HttpServletResponse
            response, org.springframework.ui.Model modelMap) {
        try {
            response.sendRedirect(new Oauth().getAuthorizeURL(request));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (QQConnectException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/oauth/checkweibo.jspx")
    public void checkweibo(String uid, String from, HttpServletRequest request, HttpServletResponse
            response, org.springframework.ui.Model modelMap) {
        try {
            response.sendRedirect(new weibo4j.Oauth().authorize("code"));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (WeiboException e) {
            e.printStackTrace();
        }
    }
}

